<script setup>
import { onMounted, ref } from 'vue'
import { getUserOrder } from '@/apis/order'
import { getAddrListAPI, AddAddrAPI, updateAddrAPI, updateUserInfoAPI, delAddrAPI } from '@/apis/user'
import { useUserStore } from '@/stores/userStore'
import { ElMessage, ElLoading } from 'element-plus'
import { regionData } from 'element-china-area-data'

const userStore = useUserStore()
const userInfo = ref({
	pic: '',
	nickName: ''
})

userInfo.value.pic = userStore.userInfo.pic
userInfo.value.nickName = userStore.userInfo.nickName

onMounted(() => getAddrList())

// 无功能提示
const handleEditInfo = () => {
	ElMessage({
		type: 'info',
		message: '敬请期待'
	})
}
const uploadRef = ref()
const avatarUrl = ref('')
// 上传文件接口地址
const action = import.meta.env.VITE_PC_BASE_PATH + '/gscloud_biz/oss/upload_minio'
// 上传文件格式限制
const accept = ref('.png, .jpg, .webp')
const fileType = ref(['png', 'jpg', 'webp'])

// 上传成功
const handleSuccess = (res, file, fileList) => {
	ElMessage({
		type: 'success',
		message: '上传成功'
	})
	avatarUrl.value = import.meta.env.VITE_PC_UPLOAD_PATH + res.data.dir + res.data.fileName
	uploadRef.value.clearFiles()
	userInfo.value.pic = avatarUrl.value
}

// 上传前校检格式和大小
const beforeUpload = (file) => {
	let isAccept = false
	if (fileType.value.length) {
		let fileExtension = ''
		if (file.name.lastIndexOf('.') > -1) {
			fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
		}

		isAccept = fileType.value.some((type) => {
			if (file.type.indexOf(type) > -1) {
				return true
			}
			if (fileExtension && fileExtension.indexOf(type) > -1) {
				return true
			}
			return false
		})
	} else {
		isAccept = file.type.indexOf('image') > -1
	}
	if (!isAccept) {
		ElMessage({
			type: 'erroe',
			message: `文件格式不正确, 请上传${fileType.value.join('/')}图片格式文件!`
		})
		return false
	}
}

// 保存个人信息
const handleSaveInfo = async () => {
	// const res = await getAddrListAPI()
	// addressList.value = res.data

	const params = {
		...userInfo.value,
		userId: userStore.userInfo.userId
	}

	await updateUserInfoAPI(params)
	await userStore.getUserInfo()
	ElMessage({
		type: 'success',
		message: '保存成功'
	})
}

// 省市区数据
const options = ref(regionData)

// 收货地址列表
const addressList = ref([])

// 获取收货地址列表
const getAddrList = async () => {
	const res = await getAddrListAPI()
	addressList.value = res.data
}
// 收货地址对象
const address = ref({
	consignee: '',
	mobile: '',
	addrCascader: '',
	addr: ''
})

// 收货地址表单校验
const rules = ref({
	consignee: [{ required: true, message: '请输入收货人', trigger: 'blur' }],
	mobile: [
		{
			required: true,
			pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
			message: '请输入正确的手机号码',
			trigger: 'blur'
		}
	],
	addrCascader: [{ required: true, message: '请输入收货地址', trigger: 'change' }],
	addr: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
})

// 弹窗标题
const title = ref('')

// 控制弹框打开
const showDialog = ref(false)

// 收货地址 收起 or 展开 状态
const addrFold = ref(false)

// 点击新增收货地址按钮
const handleAdd = () => {
	address.value = {
		consignee: '',
		mobile: '',
		addrCascader: '',
		addr: ''
	}

	showDialog.value = true
	title.value = '新增收货地址+'
}

// 编辑收货地址按钮
const handleEdit = (item) => {
	address.value = {
		...item,
		addrCascader: [item.province, item.city, item.area]
	}
	showDialog.value = true
	title.value = '编辑'
}

const ruleFormRef = ref()

// 收货地址弹窗 点击取消
const close = () => {
	showDialog.value = false
	// 清除表单校验
	ruleFormRef.value.resetFields()
}

// 收货地址弹窗点击确定
const confirm = () => {
	// const { account, password } = form.value
	// 调用实例方法
	ruleFormRef.value.validate(async (valid) => {
		// valid: 所有表单都通过校验  才为true
		// 以valid做为判断条件 如果通过校验才执行逻辑
		if (valid) {
			// TODO confirm
			const params = {
				...address.value,
				province: address.value.addrCascader[0],
				city: address.value.addrCascader[1],
				area: address.value.addrCascader[2]
			}
			if (address.value.addrId == undefined) {
				// 新增
				await AddAddrAPI(params)
				ElMessage({ type: 'success', message: '新增成功' })
			} else {
				// 编辑
				await updateAddrAPI(params)
				ElMessage({ type: 'success', message: '新增成功' })
			}
			getAddrList()
			showDialog.value = false
		}
	})
}
// 设为默认地址
const handleDefault = async (addrId) => {
	const params = {
		addrId,
		isDefault: 1
	}
	// 编辑
	await updateAddrAPI(params)
	ElMessage({ type: 'success', message: '成功设为默认地址' })
	getAddrList()
}

// 删除地址
const handleDel = async (addrId) => {
	const params = {
		addrId
	}
	// 编辑
	await delAddrAPI(params)
	ElMessage({ type: 'success', message: '删除成功' })
	getAddrList()
}
</script>

<template>
	<div class="mine">
		<div class="box box-info">
			<div class="box-item avatar">
				<div class="label">头像：</div>
				<div class="value">
					<!-- <el-upload ref="uploadRef" class="upload" :limit="1" :accept="fileType" :action="action" :on-success="handleSuccess" :before-upload="beforeUpload"> -->
					<el-upload
						ref="uploadRef"
						class="upload"
						:limit="1"
						:accept="accept"
						:action="action"
						:on-success="handleSuccess"
						:show-file-list="false"
						:before-upload="beforeUpload"
					>
						<div class="upload-btn">上传头像+</div>
					</el-upload>
					<img :src="userInfo.pic" />
				</div>
			</div>
			<div class="box-item name">
				<div class="label">昵称：</div>
				<div class="value">
					<el-input v-model="userInfo.nickName" style="width: 330px" />
				</div>
			</div>
			<el-button type="primary" @click="handleSaveInfo">保存</el-button>
		</div>
		<div class="box box-addr">
			<div class="row">
				<div class="left">我的收货地址</div>
				<div class="right" @click="handleAdd">新增收货地址+</div>
			</div>
			<div class="addr-list">
				<div class="none" v-if="!addressList.length">暂无收货地址，请新建。</div>
				<template v-else>
					<div class="item" v-for="item in addressList" :key="item.addrId">
						<div class="left">
							<span>{{ item.consignee }} <i /> {{ item.mobile }} </span>
							{{ item.province }}{{ item.city }}-{{ item.area }}-{{ item.addr }}
						</div>
						<div class="right">
							<div class="edit-btn" @click.stop="handleEdit(item)">
								<img src="../../assets/images/edit.png" alt="" />
								<span>编辑</span>
							</div>
							<div v-if="item.isDefault" class="default default-text">默认地址</div>
							<div v-else class="default default-btn" @click="handleDefault(item.addrId)">设为默认地址</div>

							<el-popconfirm title="确认删除吗?" confirm-button-text="确认" cancel-button-text="取消" @confirm="handleDel(item.addrId)">
								<template #reference>
									<div class="del-btn">×</div>
								</template>
							</el-popconfirm>
						</div>
					</div>
				</template>
			</div>
		</div>
		<!-- 切换地址 -->
		<el-dialog v-model="showDialog" :title="title" width="600px" :show-close="false" :before-close="close">
			<div class="addressWrapper">
				<el-form ref="ruleFormRef" :model="address" :rules="rules" label-width="80px">
					<el-form-item label="收货人" prop="consignee">
						<el-input v-model="address.consignee" />
					</el-form-item>
					<el-form-item label="手机号" prop="mobile">
						<el-input v-model="address.mobile" />
					</el-form-item>
					<el-form-item label="收货地址" prop="addrCascader">
						<el-cascader
							ref="cascaderRef"
							style="width: 100%"
							:options="options"
							:props="{ value: 'label' }"
							v-model="address.addrCascader"
							filterable
							placeholder="省/市/区"
						></el-cascader>
					</el-form-item>
					<el-form-item label="详细地址" prop="addr">
						<el-input type="textarea" v-model="address.addr" :rows="4" resize="none" />
					</el-form-item>
				</el-form>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="close">取消</el-button>
					<el-button type="primary" @click="confirm">保存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<style scoped lang="scss">
.mine {
	background-color: #f4f4f4;
	padding: 0 160px 30px;
	min-height: calc(100vh - 151px);
	.box {
		padding: 36px 50px 31px;
		background-color: #fff;
	}

	.box-info {
		margin-bottom: 32px;
		.box-item {
			display: flex;
			font-size: 14px;
			line-height: 21px;
			.label {
				margin-right: 16px;
				color: #999999;
			}
			.value {
				color: #333333;
				.el-input {
					height: 42px;
				}
			}
			img {
				margin-right: 16px;
				width: 128px;
				height: 128px;
				background: #d9d9d9;
				border-radius: 50%;
			}
		}
		.avatar {
			margin-bottom: 30px;
			.label {
				margin-top: 6px;
			}
			.value {
				.upload-btn {
					color: #333333;
					padding: 5px 35px;
					border: 1px solid #c1c1c1;
					border-radius: 4px;
					margin-bottom: 6px;
				}
			}
		}
		.name {
			align-items: center;
			margin-bottom: 20px;
		}
		.el-button {
			margin-left: 58px;
		}
	}
	.box-addr {
		.row {
			display: flex;
			justify-content: space-between;
			align-items: end;
			margin-bottom: 24px;
			.left {
				font-size: 24px;
				color: #333333;
				line-height: 36px;
			}
			.right {
				cursor: pointer;
				font-size: 14px;
				color: $xtxColor;
				line-height: 21px;
			}
		}
		.addr-list {
			.item {
				// min-height: 63px;
				font-size: 14px;
				line-height: 21px;
				padding: 12px 50px 12px 30px;
				border: 1px solid #f4f4f4;
				margin-bottom: 10px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				position: relative;

				.left {
					color: #333333;
					max-width: 660px;
					span {
						font-weight: 600;
						margin-right: 27px;
					}
				}
				.right {
					color: #999999;
					display: flex;
					align-items: center;
					// padding-right: 50px;
					.edit-btn {
						cursor: pointer;
						margin-right: 40px;
						img {
							background: #fff;
							width: 24px;
							height: 24px;
							margin-right: 5px;
						}
					}
					.default {
						height: 28px;
						text-align: center;
						font-size: 12px;
						line-height: 18px;
					}
					.default-btn {
						width: 80px;
						text-align: center;
						font-size: 12px;
					}

					.default-text {
						margin: 0 5px;
						width: 70px;
						background: rgba($xtxColor, 0.1);
						color: $xtxColor;
						padding: 5px 10px;
					}
					.default-btn {
						cursor: pointer;
					}
					.del-btn {
						cursor: pointer;
						position: absolute;
						right: 0;
						top: 0;
						font-size: 28px;
						// line-height: 15px;
						width: 20px;
						height: 20px;
						padding-bottom: 4px;
						display: flex;
						align-items: center;
						justify-content: center;
						border: 1px solid #999999;
						color: #333;
					}
				}
			}
		}
	}
}
</style>